package com.mybatis.service.impl;

import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.service.UserService;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author liuxiaoding
 * @Date 2019/11/8
 **/
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int delete(int id) {
        return userMapper.delete(id);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public User select(int id) {
        return userMapper.select(id);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public User selectUserInfo(Integer id) {
        return userMapper.selectUserInfo(id);
    }

    @Override
    public User selectUserShipAddress(Integer id) {
        return userMapper.selectUserShipAddress(id);
    }

    @Override
    public List<User> selectByUserIds(List<Integer> userIds) {
        if(userIds.size()>10){
            List<List<Integer>> listUserIds=ListUtils.partition(userIds,10);
            //线程池
            List<User> data=new ArrayList<>();
            try {
                ExecutorService service = Executors.newFixedThreadPool(listUserIds.size());
                BlockingQueue<Future<List<User>>> queue = new LinkedBlockingQueue<Future<List<User>>>();
                for (int i = 0; i < listUserIds.size(); i++) {
                    Future<List<User>> future = service.submit(batchRead(i,listUserIds));
                    queue.add(future);
                }
                int queueSize = queue.size();
                for (int i = 0; i < queueSize; i++) {
                    List<User> list = queue.take().get();
                    data.addAll(list);
                }
                service.shutdown();
            }catch (Exception e){
                e.printStackTrace();
            }
            return  data;

        }
        return userMapper.selectByUserIds(userIds);
    }

    private Callable<List<User>> batchRead(final int i,List<List<Integer>> userIds) {
        Callable<List<User>> callable = new Callable<List<User>>() {
            @Override
            public List<User> call() throws Exception {
                return userMapper.selectByUserIds(userIds.get(i));
            }
        };
        return callable;

    }
}
